package com.innovation.chengzhangriji.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.LoginPagerAdapter;
import com.innovation.chengzhangriji.ui.widget.SmoothTopBar;

public class LoginActivity extends BaseLoginActivity implements CuteToolbar.OnClickCuteToolbarListener, SmoothTopBar.SelectItemListener, BaseLoginFragment.LoginSuccessListener {

    private ViewPager viewPager;

    private SignUpSuccessReceive mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        SmoothTopBar smoothTopBar = (SmoothTopBar) findViewById(R.id.smooth_top_bar);
        smoothTopBar.setSelectItemListener(this);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(2);
        viewPager.setOnPageChangeListener(smoothTopBar);
        viewPager.setAdapter(new LoginPagerAdapter(getSupportFragmentManager(), this));
        registerReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {
        Intent intent = new Intent(this, SignUpActivity.class);
        startActivity(intent);
    }

    @Override
    public void selectItem(int position) {
        viewPager.setCurrentItem(position);
    }

    @Override
    public void loginSuccess(LoginInfo loginInfo) {
        // 清除所有数据
        DatabaseManager.getInstance(this).deleteAll();
        getAllBabyInfo(loginInfo);
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(Config.ACTION_SIGN_UP_SUCCESS);
        mReceiver = new SignUpSuccessReceive();
        registerReceiver(mReceiver, filter);
    }

    private void getAllBabyInfo(final LoginInfo loginInfo) {
        final String id = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        Client.requestAllBaby(this, phone, token, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Log.d("获取所有宝贝信息成功", "" + value.toString());
                AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                // 修改为直接进入Timeline
                if (response != null && response.getData() != null && response.getData().length > 0) {
                    loginInfo.setBabyID(response.getData()[0].getId());
                    setLoginInfo(loginInfo);
                    int length = response.getData().length;
                    int[] childIDArray = new int[length];
                    Auth[] auth = new Auth[length];
                    for (int i = 0; i < length; i++) {
                        childIDArray[i] = response.getData()[i].getId();
                        auth[i] = response.getData()[i].getAuth();
                    }
                    insertOrReplaceInTxBabyAndParent(id, auth, childIDArray);
                    insertOrReplaceInTxBaby(response.getData());
                    Config.startGetAllParentInfoService(LoginActivity.this);
                    startTimelineActivity();
                } else {
                    setLoginInfo(loginInfo);
                    startTimelineActivity();
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

        }, networkUnavailableSampleImpl());
    }

    private void startSelectActivity() {
        Intent intent = new Intent(LoginActivity.this, SelectActivity.class);
        startActivity(intent);
        finish();
    }

    private class SignUpSuccessReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Config.ACTION_SIGN_UP_SUCCESS)) {
                String value = intent.getStringExtra(Config.ACTION_EXTERNAL_SIGN_UP_SUCCESS_LOGIN_INFO);
                Config.setLoginInfo(context, value);
                startSelectActivity();
            }
        }
    }
}
